package cn.linkai.hadoop.zookeeper;

import org.apache.log4j.Logger;
import org.apache.zookeeper.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

public class ZooKeeperDao {

    ZooKeeper zooKeeper;
    Logger logger=Logger.getLogger(ZooKeeperDao.class);

    @Before
    public void setUp() throws IOException {
        zooKeeper=new ZooKeeper("hadoop1,hadoop2,hadoop3", 50000, watchedEvent -> {
            logger.debug("event:"+watchedEvent.getType().name());
        });
        System.out.println(zooKeeper.getSessionId());
    }
    @After
    public void tearDown() throws InterruptedException {
//        zooKeeper.close();
    }

    @Test
    public void testls() throws KeeperException, InterruptedException {
        List<String> children = zooKeeper.getChildren("/", watchedEvent -> logger.debug("event:"+watchedEvent.getType().name()));
        for (String e: children) {
            System.out.println(e);
        }
    }

    @Test
    public void reateEmphoral() throws Exception{
        ZooKeeper zk = new ZooKeeper("hadoop1:2181", 5000, null);
        zk.create( "/c" ,"tom".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

        System.out.println("hello");
    }

    @Test
    public void setData() throws KeeperException, InterruptedException {
        zooKeeper.setData("/c","tomos".getBytes(),0);
    }

    @Test
    public void getData() throws KeeperException, InterruptedException {
        byte[] data = zooKeeper.getData("/c",
                null,
                null);
        String tmp=new String(data);
        System.out.println(tmp);
    }

    @Test
    public void getDataWithWatch() throws KeeperException, InterruptedException {

        Watcher watcher=new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                System.out.println(watchedEvent.getType());
                try {
                    byte[] data = zooKeeper.getData("/c", this, null);
                    System.out.println(new String(data));
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        zooKeeper.getData("/c",watcher,null);

        while (true){
            Thread.sleep(500);
        }
    }

}
